package com.dnjn.happiness.emo.amqp;

import com.dnjn.happiness.common.amqp.AmqpConst;
import com.dnjn.happiness.common.core.exception.base.BaseException;
import com.dnjn.happiness.common.core.utils.JsonUtils;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.core.score.dto.HappyDTO;
import com.dnjn.happiness.emo.domain.vo.UserModelScoreVO;
import com.dnjn.happiness.emo.service.IUserModelScoreService;
import com.dnjn.happiness.emo.service.IUserService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class EmoAmqpReveiver {

    @Autowired
    IUserService userService;


    @Autowired
    IUserModelScoreService userModelScoreService;


    @RabbitListener(queues = AmqpConst.SCORE_RESULT_QUEUE_NAME)
    public void receiveAndConvert(/*@Payload*/ HappyDTO dto, Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        try {
            handleAmqpMessage(dto, message);
            channel.basicAck(deliveryTag, false);
        } catch (BaseException e) {
            log.error(e.getMessage(), e);
            try {
                channel.basicAck(deliveryTag, false);
            } catch (IOException ex) {
                log.warn(ex.getMessage());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);

            try {
                // basicReject一次只能拒绝接收一个消息，可以设置是否requeue。
                // basicNack方法可以支持一次0个或多个消息的拒收，可以设置是否requeue
                channel.basicNack(deliveryTag, false, true);
                // log.info("consumer receive this message: {},reject it", JsonKit.toJson(message.getBody()));
                // channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
                //channel.basicReject(deliveryTag, true);

            } catch (IOException ee) {
                log.error("exception:{}", ee.getMessage());
            }
        }
    }



    private void handleAmqpMessage(HappyDTO dto, Message message) throws Exception {
        log.info("amqp_consumer.receive.message: {} ", JsonUtils.toJsonString(dto));

        if (null == dto.getUserId()) {
            throw new BaseException("invalid.userId");
        }

        Boolean aBoolean = userService.updateHappinessScores(dto.getUserId(), dto.getModelScore().getAddScore().intValue());
        if (!aBoolean) {
            return;
        }

        UserModelScoreVO userModelScore = new UserModelScoreVO();

        BeanUtils.copyProperties(dto.getModelScore(), userModelScore);

//        userModelScore.setAiImageTotalScore(dto.getModelScore().getAiImageTotalScore());

        // todo  如果存在则更改 如果不存在则添加
        userModelScoreService.updateUserModelScore(userModelScore);
    }
}